/**
 * ImageActivity.java Create on 2012-8-3     
 *      
 * Copyright (c) 2012-8-3 by yiming     
 *      
 * @author <a href="alenzhangym@hotmail.com">Yiming</a>     
 * @version 1.0 
 */

package com.yimi.image;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.PointF; 
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.util.FloatMath;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar; 
import android.widget.Toast;
import com.yimi.actions.SearchListener; 
import com.yimi.search.AHApplication;
import com.yimi.search.SearchImageService;
import com.yimi.service.BaseImageItem;
import com.yimi.service.Entity; 
import com.yimi.util.ImageSearchUtil;

/**
 * TODO 鍔熻兘鎻忚堪
 * 
 * @author Yiming
 * @version 1.0
 */
public class ImageActivity extends Activity implements SearchListener, OnTouchListener, OnClickListener {
    private ImageView imageView;
    private AHApplication app;
    private SearchImageService searchService;
    private BaseImageItem baseImageItem;
    private byte[] bitmap;
    private Bitmap map;
    private int startPage;
    private static String TAG = "ImageActivity";
    private ProgressBar progressBar;
    Matrix matrix = new Matrix();
    Matrix savedMatrix = new Matrix();
    PointF start = new PointF();
    PointF mid = new PointF();
    float oldDist;
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    float scale;
    int mode = NONE;
    int windowwidth;
    int windowheight;
    int imageWidth;
    int imageHeight; 
    private WindowManager wm = null; 
    private WindowManager.LayoutParams wmParams = null; 
    private Button leftButton; 
    private Button rightButton; 
    private LinearLayout adcontainer; 
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        scale = 1;
        Bundle bund = this.getIntent().getExtras();
        if (bund != null) {
            Parcelable p = bund.getParcelable("baseImageItem");
            if (p != null) {
                baseImageItem = (BaseImageItem) p;
            }
        } else {
            this.finish();
        }
        this.setContentView(R.layout.imageshow);
        adcontainer = (LinearLayout) this.findViewById(R.id.subadcontainer);
        //将广告View增加到视图中。
        windowwidth = getWindowManager().getDefaultDisplay().getWidth();
        windowheight = getWindowManager().getDefaultDisplay().getHeight()-50;

        this.imageView = (ImageView) this.findViewById(R.id.bigimage);
        this.initFloatview();
        progressBar = (ProgressBar) this.findViewById(R.id.downloadprogress);
        progressBar.setVisibility(View.VISIBLE);
        progressBar.setProgress(0);
        progressBar.setMax(100);
        app = (AHApplication) this.getApplication();
        searchService = app.getSearchImageService();
        searchService.registerSearchListener(this);
        String path = this.baseImageItem.getFileURL();
        int index = path.lastIndexOf('/');
        path = path.substring(index + 1);
        bitmap = ImageSearchUtil.getPictureFromFile(ImageSearchUtil.sdcardFilePath,path);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (bitmap != null) {
            map = BitmapFactory.decodeByteArray(bitmap, 0, bitmap.length);
            progressBar.setVisibility(View.GONE);
            imageView.setImageBitmap(map);
            imageWidth = imageView.getDrawable().getIntrinsicWidth();
            imageHeight = imageView.getDrawable().getIntrinsicHeight(); 
            imageView.setOnTouchListener(this);
        } else {
            if (this.checkNetworkInfo()) {
                searchService.queryImageFileView(baseImageItem.getFileURL());
            } else {
                this.finish();
            }
        }
    }
    
    public void onResume(){
        super.onResume();
        createButtons();
    }
    private void createButtons(){
        leftButton = new Button(this); 
        rightButton = new Button(this);
        createLeftButton();
    }
    private void initFloatview() { 
        wm = (WindowManager) getApplicationContext().getSystemService("window"); 
    }
    
    private void createLeftButton() { 
        wmParams = new WindowManager.LayoutParams(); 
        wmParams.type = LayoutParams.TYPE_PHONE; 
        wmParams.format = PixelFormat.RGBA_8888; 
        wmParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL 
        | LayoutParams.FLAG_NOT_FOCUSABLE; 
        leftButton.setBackgroundResource(R.drawable.filter_left_btn_selecor); 
        leftButton.getBackground().setAlpha(100);  
        rightButton.setBackgroundResource(R.drawable.filter_right_btn_selecor);
        rightButton.getBackground().setAlpha(100);
        leftButton.setOnClickListener(this); 
        wmParams.width = 210; 
        wmParams.height = 80; 
        wmParams.gravity = Gravity.LEFT | Gravity.BOTTOM; 
        wmParams.x = 30; 
        wmParams.y = 10; 
        wm.addView(leftButton, wmParams); 
        wmParams.width = 210; 
        wmParams.height = 80; 
        wmParams.gravity = Gravity.RIGHT | Gravity.BOTTOM; 
        wmParams.x = 30; 
        wmParams.y = 10;
        wm.addView(rightButton, wmParams); 
        rightButton.setOnClickListener(this); 
        } 
    /*
     * (non-Javadoc)
     * @see com.yimi.actions.SearchListener#onEvent(int, int,
     * com.yimi.service.Entity)
     */
    @Override
    public void onEvent(int event, int type, Entity object) {
//        if (event == MessageType.EVENT_QUDERYFILEVIEWSUCCESS) {
//            ImageEntity imageEntity = (ImageEntity) object;
//            if (imageEntity.getFileURL().equals(this.baseImageItem.getFileURL())) {
//                if (bitmap == null) {
//                    bitmap = new byte[imageEntity.getImageSize()];
//                    progressBar.setMax(imageEntity.getImageSize());
//                    Log.e(TAG, " bitmap lenth is " + bitmap.length);
//                    startPage = 0;
//                }
//                byte[] src = imageEntity.getImage();
//                Log.e(TAG, " start to copy src lenth is " + src.length);
//                if(src.length>0){
//                    System.arraycopy(src, 0, bitmap, startPage, src.length);
//                }
//                startPage += src.length;
//                progressBar.setProgress(startPage);
//                Log.e(TAG, " bitmap now lenth is " + startPage);
//                if (type == MessageType.TYPE_DOWNLOAD_END) {
//                    Log.e(TAG, " download over");
//                    String fileName = this.baseImageItem.getFileURL();
//                    int index = fileName.lastIndexOf('/');
//                    if (ImageSearchUtil.isSDCardAvailable()) {
//                        if (ImageSearchUtil.getSDCardSize() > bitmap.length) {
//                            fileName = fileName.substring(index + 1);
//                            ImageSearchUtil.createFile(ImageSearchUtil.filePath,fileName);
//                            ImageSearchUtil.savePictureToFile(bitmap, fileName,ImageSearchUtil.filePath);
//                        } else {
//                            Toast t = Toast.makeText(this, "SD卡空间不足，不能保存图片本地", 3000);
//                            t.show();
//                        }
//                    }
//                    map = BitmapFactory.decodeByteArray(bitmap, 0, bitmap.length);
//                    progressBar.setVisibility(View.GONE);
//                    this.imageView.setImageBitmap(map);
//                    imageWidth = imageView.getDrawable().getIntrinsicWidth();
//                    imageHeight = imageView.getDrawable().getIntrinsicHeight();
//                    imageView.setOnTouchListener(this);
//                    imageView.setClickable(true);
//                    imageView.invalidate(); 
//                }
//            }
//        } else if (event == MessageType.EVENT_QUERYFILEVIEWFAILED) {
//            ImageEntity imageEntity = (ImageEntity) object;
//            if (imageEntity.getFileURL().equals(this.baseImageItem.getFileURL())) {
//                Toast t = Toast.makeText(this, "查询失败", 6000);
//                if (type == MessageType.TYPE_QUERYMAP_HTTPFAILED) {
//                    t = Toast.makeText(this, "连接服务失败", 6000);
//                } else if (type == MessageType.TYPE_QUEYRMAP_FAILED) {
//                    t = Toast.makeText(this, "查询失败", 6000);
//                } else if (type == MessageType.TYPE_QUERYMAP_TOOLARGER) {
//                    t = Toast.makeText(this, "图片太大,不可下载哦", 6000);
//                }
//                t.show();
//            }
//        }
    }
    
    protected void onPause() { 
       // TODO Auto-generated method stub 
       super.onPause();  
       wm.removeView(leftButton); 
       wm.removeView(rightButton);
     } 
    
    public void onDestroy() {

        super.onDestroy();
    }

    public void onBackPressed() {
        progressBar.clearAnimation();
        searchService.unRegisterSearchListener(this);
        searchService.cancelDownloadImage(baseImageItem.getFileURL());
        if (map != null) {
            map.recycle();
        }
        Intent intent = new Intent(this,
                SearchActivity.class);
        this.startActivity(intent);
        this.finish();
    }

    public boolean onTouch(View v, MotionEvent event) {
        // Handle touch events here...
        ImageView view = (ImageView) v;

        Log.e(TAG, " imageWidth   " + imageWidth);
        Log.e(TAG, "imageHeight " + imageHeight);

        // Handle touch events here...
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                savedMatrix.set(matrix);
                start.set(event.getX(), event.getY());
                Log.d(TAG, "mode=DRAG");
                scale = 1;
                mode = DRAG;
                break;

            case MotionEvent.ACTION_UP:
                // 閲婃斁鎵嬪娍鍔ㄤ綔
//                savedMatrix.set(matrix); 
                if (mode == DRAG) {
//                    matrix.set(savedMatrix);     
                    Log.e(TAG, "width is " + imageWidth);
                    Log.e(TAG, "height is " + imageHeight);
                    float vs[] = new float[9];
                    Matrix m = imageView.getImageMatrix();
                    m.getValues(vs);
                    float top = vs[Matrix.MTRANS_Y];
                    float left = vs[Matrix.MTRANS_X];
                    float bottom = top + imageHeight;
                    float right = left + imageWidth;
                    Log.e(TAG, "top is " + top);
                    Log.e(TAG, "bottom is " + bottom);
                    Log.e(TAG, "left is " + left);
                    Log.e(TAG, "right is " + right);
                    Log.e(TAG, "windowwidth is " + windowwidth);
                    Log.e(TAG, "windowheight is " + windowheight);
                    boolean needReturn= true;
                    boolean needYReturn =true;
                    boolean needXReturn = true;
                    float dx = 0;
                    float dy =0;
                    //注意，放大倍数的固定，
                    if(top<=0&&left<=0&&bottom>=windowheight&&right>=windowwidth){
                        //完全超出了屏幕范围
                        needReturn = false;
                    }
                    if(top>=0&&left>=0&&bottom<=windowheight&&right<=windowwidth){
                        //完全在屏幕范围以内
                        needReturn = false;
                    }
                    if(needReturn){
                        if(top<=0&&bottom>=windowheight){
                            needYReturn = false;
                        }
                        if(top>0&&bottom<windowheight){
                            needYReturn = false;
                        }
                        if(needYReturn){
                            if(top<=0){
                                 if(imageHeight<windowheight)
                                 {
                                     dy=-top;
                                  }
                                 else{
                                     dy =  windowheight-bottom;
                                 }
                            }else{
                                if(imageHeight<windowheight)
                                 {
                                        dy=windowheight-bottom;
                                 }else{
                                     dy=-top;
                                 }
                            }
                        }
                        if(left<=0&&right>=windowwidth){
                            needXReturn = false;
                        }
                        if(left>0&&right<windowwidth){
                            needXReturn = false;
                        }
                        if(needXReturn){
                            if(left<0){
                                if(imageWidth>windowwidth){
                                    dx = windowwidth-right;
                                }else{
                                    dx=-left;
                                }
                            }else{
                                if(imageWidth>windowwidth){
                                    dx = -left;
                                }else{
                                    dx=windowwidth-right;
                                }
                            }
                        }
                        if(needXReturn||needYReturn){
                            matrix.postTranslate(dx,
                                    dy);
                        }
                    }
                }
                mode = NONE;
                break;
            case MotionEvent.ACTION_POINTER_UP:
               
                imageHeight = (int) (imageHeight * scale);
                imageWidth = (int) (imageWidth * scale);
                scale = 1;
                mode = NONE;
                Log.d(TAG, "mode=NONE");
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                Log.d(TAG, "oldDist=" + oldDist);
                if (oldDist > 10f) {
                    savedMatrix.set(matrix);
                    midPoint(mid, event);
                    mode = ZOOM;
                    Log.d(TAG, "mode=ZOOM");
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    matrix.set(savedMatrix);  
                    float dx = event.getX() - start.x;
                    float dy = event.getY() - start.y;
                    matrix.postTranslate(dx,
                            dy);
                } else if (mode == ZOOM) {
                    float newDist = spacing(event);
                    Log.d(TAG, "newDist=" + newDist);
                    if (newDist > 10f) {
                        matrix.set(savedMatrix);
                        scale = newDist / oldDist;
                        Log.d(TAG, "matrix postScale start scale is " + scale);
                        matrix.postScale(scale, scale, mid.x, mid.y);
                    }
                }
                break;
        }
        view.setImageMatrix(matrix);
        return true;
    }

    private boolean checkNetworkInfo()
    {
        ConnectivityManager conMan = (ConnectivityManager) this
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        // mobile 3G Data Network

        State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();

        // 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接

        if (wifi == State.CONNECTED || wifi == State.CONNECTING)
            return true;
        Toast t = Toast.makeText(this, "请先设置无线网络，下载图片", 3000);
        t.show();
        this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));// 进入无线网络配置界面
        // startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
        // //进入手机中的wifi网络设置界面

        return false;
    }

    /*
     * (non-Javadoc)
     * @see android.view.View.OnTouchListener#onTouch(android.view.View,
     * android.view.MotionEvent)
     */
    private float spacing(MotionEvent event) {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }

    // 璁＄畻涓偣浣嶇疆
    private void midPoint(PointF point, MotionEvent event) {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }

    /* (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        if(map==null){
            return;
        }
        if(v==leftButton){
            Matrix matrix = new Matrix(); 
            matrix.postRotate(-90);
            imageWidth = imageView.getDrawable().getIntrinsicWidth();
            imageHeight = imageView.getDrawable().getIntrinsicHeight();
            Bitmap resizedBitmap = Bitmap.createBitmap(map,0, 0, 
                    imageWidth, imageHeight, matrix, true); 
            this.imageView.setImageBitmap(resizedBitmap);
            this.map.recycle();
            this.map = resizedBitmap;
            savedMatrix.set(matrix);
//            this.imageView.setImageMatrix(matrix);
            imageWidth = imageView.getDrawable().getIntrinsicWidth();
            imageHeight = imageView.getDrawable().getIntrinsicHeight();
       }else if(v==rightButton){
           Matrix matrix = new Matrix(); 
           matrix.postRotate(90);
           savedMatrix.set(matrix);
           imageWidth = imageView.getDrawable().getIntrinsicWidth();
           imageHeight = imageView.getDrawable().getIntrinsicHeight();
           Bitmap resizedBitmap = Bitmap.createBitmap(map,0, 0, 
                   imageWidth, imageHeight, matrix, true); 
           this.imageView.setImageBitmap(resizedBitmap);
           this.map.recycle();
           this.map = resizedBitmap;
//           this.imageView.setImageMatrix(matrix);
           imageWidth = imageView.getDrawable().getIntrinsicWidth();
           imageHeight = imageView.getDrawable().getIntrinsicHeight();
       }
    }
}
